const router = require("koa-router")();
const fs = require("fs-extra");
const path = require("path");
const { Payment } = require("wechat-pay");

/**
 *
 * api {get} /home/app/plugins/payWxa/config 获取微信支付配置
 *
 */
router.get("/payWxa/config", async (ctx, nex) => {
  const baas = ctx.baas;
  const config = await BaaS.Models.pay_wxa
    .query({ where: { baas_id: baas.id } })
    .fetch({ withRelated: ["class", "function"] });
  ctx.success(config);
});
/**
 *
 * api {get} /home/app/plugins/payWxa/config 提交微信支付配置
 *
 */
router.post("/payWxa/config", async (ctx, nex) => {
  const baas = ctx.baas;
  const { appid = "", mchid = "", key = "" } = ctx.post;

  const wxaPay = await BaaS.Models.pay_wxa
    .query({ where: { baas_id: baas.id } })
    .fetch();
  const id = wxaPay.id;
  // 验证表单是否为空
  const isEmpty = ctx.isEmpty(
    {
      appid: appid,
      mchid: mchid,
      key: key
    },
    ["appid", "mchid", "key"]
  );
  if (!isEmpty) {
    ctx.error("请完善表单");
    return;
  }
  const config = await BaaS.Models.pay_wxa
    .forge({
      id: id,
      baas_id: baas.id,
      appid: appid,
      mchid: mchid,
      key: key
    })
    .save();
  ctx.success(config);
});
/**
 *
 * api {get} /home/app/plugins/payWxa/config 提交微信支付回调
 *
 */
router.post("/payWxa/payCall", async (ctx, next) => {
  const baas = ctx.baas;
  const classId = ctx.post.class_id;
  const functionId = ctx.post.function_id;
  // 验证表单是否为空
  const isEmpty = ctx.isEmpty(
    {
      function_id: functionId,
      class_id: classId
    },
    ["class_id", "function_id"]
  );
  if (!isEmpty) {
    ctx.error("请完善表单");
    return;
  }
  // 查询是否已配置过
  const wxaConfig = await BaaS.Models.pay_wxa
    .query({
      where: { baas_id: baas.id }
    })
    .fetch();
  if (wxaConfig) {
    await BaaS.Models.pay_wxa
      .forge({
        id: wxaConfig.id,
        function_id: functionId,
        class_id: classId
      })
      .save();
  } else {
    await BaaS.Models.pay_wxa
      .forge({
        function_id: functionId,
        class_id: classId
      })
      .save();
  }
  ctx.success("提交成功");
});
/**
 *
 * api {get} /home/app/plugins/payWxa/config 提交微信支付证书
 *
 */
router.post("/payWxa/uploadCert", async (ctx, next) => {
  const baas = ctx.baas;
  const file = ctx.file.file;

  if (
    file.type != "application/x-pkcs12" &&
    file.name != "apiclient_cert.p12"
  ) {
    await fs.remove(file.path);
    ctx.error("请上传正确的证书");
    return;
  }
  // 查询是否已存在
  const wxaConfig = await BaaS.Models.pay_wxa
    .query({
      where: { baas_id: baas.id }
    })
    .fetch();
  // 读取支付证书，存于数据库
  const certificate = JSON.stringify(fs.readFileSync(file.path));
  const err = await BaaS.Models.pay_wxa
    .forge({
      id: wxaConfig.id,
      baas_id: baas.id,
      certificate: certificate
    })
    .save();
  if (err) {
    console.log(err);
  }
  ctx.success("上传成功");
});
// 微信支付
router.get("/payWxa", async (ctx, next) => {
  const baas = ctx.baas;
  const wxPay = await BaaS.Models.pay_wxa
    .query({ where: { baas_id: baas.id } })
    .fetch();
  const payment = new Payment({
    partnerKey: wxPay.key,
    appId: this.state.wxa.authorizer_appid,
    mchId: wxPay.mchid,
    notifyUrl: notifyUrl,
    pfx: wxPay.certificate
  });
});

module.exports = router;
